package com.cn.client.remplance;

import com.cn.client.AllocateMessageQueueStrategy;
import com.cn.common.MessageQueue;
import com.cn.exception.MyException;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class AllocateMessageQueueStrategyAverage implements AllocateMessageQueueStrategy {


    @Override
    public List<MessageQueue> allocate(String group, List<MessageQueue> mqs, List<String> cidAll, String clientId) {
        if (mqs == null || mqs.size() == 0) {
            throw new MyException("消息队列为空！");
        }
        if (cidAll == null || cidAll.size() == 0) {
            throw new MyException("消费节点为空！");
        }
        if (StringUtils.isEmpty(clientId)) {
            throw new MyException("当前消费端id不能为空！");
        }
        List<MessageQueue> result = new ArrayList<>();

        //当前消费端节点索引
        int index = cidAll.indexOf(clientId);
//        System.out.println("cids:" + cidAll);
//        System.out.println("clienetId:" + clientId);
//        System.out.println("index:" + index);
        if (index < 0) {
            throw new MyException(AllocateMessageQueueStrategy.class.getName() + "消费端注册失败！");
        }

        // (队列总数 % 节点总数)
        int mod = mqs.size() % cidAll.size();
        /**
         * 1. 如果 队列长度 小于 节点长度，那么默认为1
         * 2. 如果 队列长度 大于 节点长度，
         */
        int averageSize =
                mqs.size() <= cidAll.size() ? 1 : (mod > 0 && index < mod ? mqs.size() / cidAll.size()
                        + 1 : mqs.size() / cidAll.size());
        int startIndex = (mod > 0 && index < mod) ? index * averageSize : index * averageSize + mod;
        int range = Math.min(averageSize, mqs.size() - startIndex);
        for (int i = 0; i < range; i++) {
            result.add(mqs.get((startIndex + i) % mqs.size()));
        }
        return result;
    }

    @Override
    public String getName() {
        return "AVG";
    }
}
